package cn.south.campus.admin.interceptor;

import cn.south.campus.common.utils.GenSerializeUtil;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/14 10:12
 */
@Component
public class TraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) {
        String traceId = GenSerializeUtil.genTraceId();
        MDC.put("traceId", traceId);
        return true;
    }

    @Override
    public void afterCompletion(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler,
                                @Nullable Exception ex) throws Exception {
        MDC.clear();
    }
}
